package server;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Client
{

    String targetURL = "http://localhost:8000";    
    HttpURLConnection connection = null;
    URL url;

    public static void main(String args[])
    {

        Client client = new Client();    
        client.sendInfo("hey!");                
        System.out.println(client.getResponse());
        client.sendInfo("bye!");                
        System.out.println(client.getResponse());
    }

    private void createConnection()
    {
        try
        {            
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/html");
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setAllowUserInteraction(true);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }

    }

    /**
    * Sends information to server.    
    */
    public void sendInfo(String myInfo)
    {
        createConnection();
        try
        {
            DataOutputStream wr = null;
            wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(myInfo);
            wr.flush();
            wr.close();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

   /**
    * Reads response from server.
    * Should be called instantly after sendInfo() method.
    */
    public String getResponse()
    {
        String ret = null;
        try
        {

            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null)
            {
                response.append(line);
                response.append('\n');
            }
            rd.close();

            ret = response.toString();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }       
        return ret;
    }
}
